package com.ladlee.validata.processor.impl;

import com.ladlee.enums.ResultEnum;
import com.ladlee.validata.ValidataCodeType;
import com.ladlee.validata.ValidateCode;
import com.ladlee.validata.ValidateCodeGenerator;
import com.ladlee.validata.exception.ValidateCodeException;
import com.ladlee.validata.processor.ValidateCodeProcessor;
import com.ladlee.validata.processor.ValidateCodeRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.ServletWebRequest;

import java.util.Map;

/**
 * @Auther: dingchang
 * @Date: 2018/12/21 15:50
 * @Description: 验证码处理器,创建验证码和校验验证码，发送验证码有具体子类实现
 */
public abstract class AbstractValidateCodeProcessor<C extends ValidateCode> implements ValidateCodeProcessor {

    /**
     * 收集系统所有{@link ValidateCodeGenerator} 接口的实现。
     */
    @Autowired
    private Map<String, ValidateCodeGenerator> validateCodeGenerators;

    @Autowired
    private ValidateCodeRepository validateCodeRepository;

    @Override
    public void create(ServletWebRequest request) throws Exception {
        C c = generatorCode();
        save(request,c);//session保存验证码
        send(request,c);//发送验证码
    }

    @Override
    public void validate(ServletWebRequest request) {
        ValidataCodeType validateCodeType = getValidateCodeType();//验证码类型
        C codeInSession = (C) validateCodeRepository.get(request, validateCodeType);//从session里面获取验证码
        String codeInRequest;//请求里面的验证码
        try {
            codeInRequest = ServletRequestUtils.getStringParameter(request.getRequest(), validateCodeType.getParamNameOnValidate());
        } catch (ServletRequestBindingException e) {
            throw new ValidateCodeException(ResultEnum.CODE_ERROT.getCode(),"获取验证码的值失败");
        }

        if (StringUtils.isBlank(codeInRequest)) {
            throw new ValidateCodeException(ResultEnum.CODE_ERROT.getCode(),validateCodeType + "验证码的值不能为空");
        }

        if (codeInSession == null) {
            throw new ValidateCodeException(ResultEnum.CODE_ERROT.getCode(),validateCodeType + "验证码不存在");
        }

        if (codeInSession.isExpired()) {
            validateCodeRepository.remove(request, validateCodeType);
            throw new ValidateCodeException(ResultEnum.CODE_ERROT.getCode(),validateCodeType + "验证码已过期");
        }
        if (!StringUtils.equals(codeInSession.getCode(), codeInRequest)) {
            throw new ValidateCodeException(ResultEnum.CODE_ERROT.getCode(),validateCodeType + "验证码不匹配");
        }

        validateCodeRepository.remove(request, validateCodeType);

    }

    private void save(ServletWebRequest request,C validateCode){
        ValidateCode code = new ValidateCode(validateCode.getCode(),validateCode.getExpireTime());
        validateCodeRepository.save(request,code,getValidateCodeType());
    }

    /**
     * 生成验证码
     * @return
     */
    private C generatorCode(){
        String type = getValidateCodeType().toString().toLowerCase();
        String generatorName = type + ValidateCodeGenerator.class.getSimpleName();
        ValidateCodeGenerator validateCodeGenerator = validateCodeGenerators.get(generatorName);
        if (validateCodeGenerator == null) {
            throw new ValidateCodeException("验证码生成器" + generatorName + "不存在");
        }
        return (C)validateCodeGenerator.generate();
    }

    /**
     * 根据Holder返回得CodeProcessor类型来获取验证码的类型
     * @return
     */
    private ValidataCodeType getValidateCodeType(){
        String type = StringUtils.substringBefore(getClass().getSimpleName(),"CodeProcessor");
        return ValidataCodeType.valueOf(type.toUpperCase());
    }

    /**
     * 发送校验码，由子类实现
     *
     * @param request
     * @param validateCode
     * @throws Exception
     */
    protected abstract void send(ServletWebRequest request, C validateCode) throws Exception;
}
